package preorder

import (
    "time"
	"strconv"
	"dhfshop/controllers/base"
	"dhfshop/models/preorder"
	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
)

type PreOrderOptController struct {
	base.BaseController
}

func (this *PreOrderOptController) CfgInit() {
	partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	storeIdStr := this.GetString("store_id")
	if storeIdStr == "" {
	    this.ServeError("store_id is null")
	    return
	}
	storeId, err := strconv.ParseInt(storeIdStr, 10, 64)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	if err := preorder.DeletePreOrderOptByPartnerId(partnerId, storeId); err != nil {
	    //this.ServeError(err.Error())
		//return
	}
	if err := preorder.InitDefaultPreOrderOpt(partnerId, storeId); err != nil {
	    this.ServeError(err.Error())
		return
	}
	opt, err := preorder.GetPreOrderOptByPartnerId(partnerId, storeId)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	this.Data["json"] = opt
	this.ServeJSON()
}

func (this *PreOrderOptController) List() {
	query,_, fields, order_by, offset, limit, err := this.GetQueryPara()
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	partnerId := int64(this.Ctx.Input.GetData("curCompanyId").(int))
	query["partner_id"] = strconv.FormatInt(partnerId, 10)
	l, cnt, err := preorder.GetAllPreOrderOpts(query, fields, order_by, offset, limit)
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	r := struct {
		TotalCount   int64               `json:"total_count"`
		PreOrderOpt []*preorder.PreOrderOpt `json:"subsys_opts"`
	}{TotalCount: cnt, PreOrderOpt: l}
	this.Data["json"] = r
	this.ServeJSON()
}

func (this *PreOrderOptController) Update() {
	var v preorder.PreOrderOpt
	this.ParseForm(&v)
	valid := validation.Validation{}
	valid.Required(v.PreOrderOptId, "pre_order_opt_id")
	valid.Required(v.StoreId, "store_id")
	valid.Range(v.CanCancelDays, 1, 30,"can_cancel_days")
	valid.Range(v.CanReserveDays, 1, 30,"can_reserve_days")
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key + " " + valid.Errors[0].Message)
		return
	}
	updateFields, err := this.GetUpdateFields(v, "", "form", []string{"print_pub_id"})
	if err != nil {
		this.ServeError(err.Error())
		return
	}
	if len(updateFields) > 0 {
		err := preorder.UpdatePreOrderOptById(&v, updateFields...)
		if err != nil {
			this.ServeError(err.Error())
			return
		}
	}
	rsp := struct {
		PreOrderOptId  int64     `json:"preorder_opt_id"`
		Modified     time.Time `json:"modified"`
	}{PreOrderOptId: v.PreOrderOptId, Modified: time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}
